// VS Code API 工具函数
export interface VsCodeApi {
  postMessage(message: any): void;
  getState(): any;
  setState(state: any): void;
}

// 获取 VS Code API 实例
export function getVsCodeApi(): VsCodeApi {
  // 如果已经存在全局实例，直接返回
  if ((window as any).vscode) {
    return (window as any).vscode;
  }

  try {
    // 尝试获取 VS Code API
    const vscode = (window as any).acquireVsCodeApi();
    (window as any).vscode = vscode;
    return vscode;
  } catch (error) {
    console.warn('VS Code API not available, running in development mode');
    // 开发模式下提供 mock API
    const mockApi: VsCodeApi = {
      postMessage: (message: any) => {
        console.log('Mock postMessage:', message);
      },
      getState: () => ({}),
      setState: (state: any) => console.log('Mock setState:', state)
    };
    (window as any).vscode = mockApi;
    return mockApi;
  }
}

// 发送消息到 VS Code 扩展的便捷函数
export function sendMessage(command: string, data?: any) {
  const vscode = getVsCodeApi();
  vscode.postMessage({ command, data });
}